import numpy as np
import soundfile as sf

import soundfile as sf

def extract_watermark(audio_path, watermark_length):
    audio, _ = sf.read(audio_path)
    watermarks = []
    if audio.ndim > 1:
        for channel in range(audio.shape[1]):
            channel_audio = audio[:, channel]
            # 提取当前声道的水印
            channel_audio_int = (channel_audio * (2 ** 15)).astype(np.int16)
            watermark_bin = ''.join([str(channel_audio_int[i] & 1) for i in range(watermark_length)])
            # 二进制转字符串
            watermark = ''
            for i in range(0, watermark_length, 8):
                byte = watermark_bin[i:i + 8]
                watermark += chr(int(byte, 2))
            watermarks.append(watermark)
    else:
        audio_int = (audio * (2 ** 15)).astype(np.int16)
        watermark_bin = ''.join([str(audio_int[i] & 1) for i in range(watermark_length)])
        # 二进制转字符串
        watermark = ''
        for i in range(0, watermark_length, 8):
            byte = watermark_bin[i:i + 8]
            watermark += chr(int(byte, 2))
        watermarks.append(watermark)
    return watermarks



# 示例：提取8字节水印（如日期长度）
print(extract_watermark("output.wav", 128))  # 输出：2025-03-30